package comm

// 存放String相关操作方法

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"reflect"
	"strings"
	"unsafe"
)

func String2Bytes(str string) []byte {
	ssh := (*reflect.StringHeader)(unsafe.Pointer(&str))
	bsh := &reflect.SliceHeader{
		Data: ssh.Data,
		Len:  ssh.Len,
		Cap:  ssh.Len,
	}
	return *(*[]byte)(unsafe.Pointer(bsh))
}

func Bytes2String(bytes []byte) string {
	bsh := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))
	ssh := &reflect.StringHeader{
		Data: bsh.Data,
		Len:  bsh.Len,
	}
	return *(*string)(unsafe.Pointer(ssh))
}

func String2Bool(str string) (bool, error) {
	ls := strings.ToLower(str)

	if ls == "true" {
		return true, nil
	}

	if ls == "false" {
		return false, nil
	}

	return false, errors.New("not bool string: " + str)
}

func StrSliceContains(ss []string, s string) bool {
	for _, v := range ss {
		if v == s {
			return true
		}
	}

	return false
}

func StrMD5Sum(str string) string {
	sum := md5.Sum(String2Bytes(str))
	return hex.EncodeToString(sum[:])
}
